package com.cwf.quality.common.strategy.analyzer;

import com.cwf.quality.common.enums.DataAnalyzerEnum;
import com.cwf.quality.model.dto.QualityResultInfo;
import com.cwf.quality.model.dto.dataanalyze.param.AnalyzerParamInfo;
import com.cwf.quality.model.dto.dataanalyze.result.AvgAnalyzeResult;
import com.cwf.quality.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class AvgDataAnalyzer implements IDataAnalyzer {

    /**
     * 平均值计算
     *
     * @param analyzerParamInfo
     * @return
     */
    @Override
    public QualityResultInfo<List<AvgAnalyzeResult>> analyzeData(AnalyzerParamInfo analyzerParamInfo) {
        SqlUtils sqlUtils = analyzerParamInfo.getSqlUtils();

        List<AvgAnalyzeResult> avgAnalyzeResultList = new ArrayList<>();

        List<String> columnNameList = analyzerParamInfo.getColumnNameList();
        for (String columnName : columnNameList) {
            // 生成空值校验的SQL
            String sql = DataAnalyzerEnum.AVG_ANALYZE.getSql()
                    .replace("{table}", analyzerParamInfo.getTableName())
                    .replace("{column}", columnName);

            List<Map<String, Object>> mapList = sqlUtils.query4List(sql, 1);
            BigDecimal avg = (BigDecimal) mapList.get(0).get("avg");
            avgAnalyzeResultList.add(AvgAnalyzeResult.builder().columnName(columnName).avg(avg).build());
        }
        QualityResultInfo qualityResultInfo = QualityResultInfo.builder()
                .code(0)
                .msg("成功")
                .result(avgAnalyzeResultList)
                .build();
        return qualityResultInfo;
    }
}
